/*
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package botobjects;

import interfaces.BotObject;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import main.Constants;

import org.apache.log4j.Logger;
import org.jibble.pircbot.Colors;

import tools.StringTools;
import database.DBConnectionFactory;

/**
 * Represents an order
 * 
 * 
 */
public class Order implements BotObject {
   /**
    * Removes the specified order
    * 
    * @param args
    *           Specifies the ID of the order to be removed
    * @return true if the order is successfully deleted
    */
   public static boolean deleteFromDB(final String... args) {
	  boolean out = false;
	  int id = 0;
	  try {
		 id = Integer.parseInt(args[0]);
	  } catch (NumberFormatException e) {
		 Logger.getLogger("Error").error("", e);
		 return out;
	  }
	  if (args.length < 1 || id < 0)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection().prepareStatement("DELETE FROM orders WHERE id = ?");
		 ps.setInt(1, Integer.parseInt(args[0]));
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }

   /**
    * Returns a list of all orders
    * 
    * @return a List of Order objects
    */
   public static List<Order> getOrders() {
	  List<Order> out = new LinkedList<Order>();
	  PreparedStatement ps = null;
	  ResultSet rs = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("SELECT * FROM orders ORDER BY category, settime DESC");
		 rs = ps.executeQuery();

		 while (rs.next()) {
			out.add(new Order(rs.getInt("id"), rs.getString("message"), rs.getString("recipient"), rs.getString("category"), rs
				  .getTimestamp("settime").getTime()));
		 }
	  } catch (SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			rs.close();
		 } catch (SQLException e) {
		 }
		 try {
			ps.close();
		 } catch (SQLException e) {
		 }
	  }
	  return out;
   }

   private int id = 0;
   private String order = "";
   private String orderTo = "";

   private String category = "";

   private Long time = 0L;

   public Order(final int id, final String order, final String orderTo, final String category, final Long time) {
	  this.id = id;
	  this.order = order;
	  this.orderTo = orderTo;
	  this.category = category;
	  this.time = time;
   }

   public String getCategory() {
	  return category;
   }

   public int getId() {
	  return id;
   }

   @Override
   public List<String> getIRCOutput(final int outputType, final String... args) {
	  List<String> out = new LinkedList<String>();
	  if (args.length < 2 || StringTools.isNullOrEmpty(getOrder()) || getOrderTo() == null || getTime() == null)
		 return out;
	  String pattern = "EEE, MMM d, H:mm:ss";
	  SimpleDateFormat sdf = new SimpleDateFormat(pattern, Locale.US);
	  Date irlTime = new Date(getTime());
	  TimeZone tz = TimeZone.getTimeZone("GMT" + args[0]);
	  sdf.setTimeZone(tz);

	  out.add(("".equals(getCategory()) ? "[?] " : "[" + getCategory() + "] ")
			+ (outputType == Constants.ORDERS_NEW_ONLY ? "" : Colors.BLUE + args[1] + ": ") + Colors.NORMAL
			+ (!getOrderTo().equals("") ? Colors.DARK_GREEN + "For " + getOrderTo() + ": " : "") + Colors.RED + getOrder()
			+ Colors.BLUE + " Added: " + sdf.format(irlTime));
	  return out;
   }

   public String getOrder() {
	  return order;
   }

   public String getOrderTo() {
	  return orderTo;
   }

   @Override
   public Map<String, Object> getRPCOutput(final int... includes) {
	  Map<String, Object> out = new HashMap<String, Object>();
	  if (StringTools.isNullOrEmpty(getOrder()) || getOrderTo() == null || getTime() == null)
		 return out;
	  out.put("ID", getId());
	  out.put("Order", getOrder());
	  out.put("Recipient", getOrderTo());
	  out.put("Added Time", new Date(getTime()));
	  return out;
   }

   public Long getTime() {
	  return time;
   }

   @Override
   public boolean saveToDB() {
	  boolean out = false;
	  if (StringTools.isNullOrEmpty(getOrder()) || getOrderTo() == null || getTime() == null)
		 return out;
	  PreparedStatement ps = null;
	  try {
		 ps = DBConnectionFactory.getConnectionHandler().getConnection()
			   .prepareStatement("INSERT INTO orders VALUES(default,?,?,?,?)");
		 ps.setString(1, getOrder());
		 ps.setTimestamp(2, new Timestamp(Calendar.getInstance().getTimeInMillis()));
		 ps.setString(3, getOrderTo());
		 ps.setString(4, getCategory());
		 if (ps.executeUpdate() == 1) {
			out = true;
		 }
	  } catch (final SQLException e) {
		 Logger.getLogger("Error").error("", e);
	  } finally {
		 try {
			ps.close();
		 } catch (final Exception e) {
		 }
	  }
	  return out;
   }
}
